package x.ovo.wechat.bot.impl.http;

import lombok.Getter;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import org.jetbrains.annotations.NotNull;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 默认 Cookie 存储
 *
 * @author ovo on 2024/07/08.
 */
public enum DefaultCookieStore implements CookieJar {
    INSTANCE;

    @Getter
    private final static Map<String, List<Cookie>> Store = new HashMap<>();

    public static List<HttpCookie> getCookies() {
        return Store.values().stream()
                .flatMap(List::stream)
                .map(Cookie::toString)
                .map(HttpCookie::parse)
                .flatMap(List::stream)
                .toList();
    }

    public static void setCookies(Map<String, List<Cookie>> cookies) {
        Store.putAll(cookies);
    }

    @NotNull
    @Override
    public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
        return Store.getOrDefault(httpUrl.host(), List.of());
    }

    @Override
    public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
        Store.put(httpUrl.host(), list);
    }
}
